package homework2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageCopier {
    
    public static void main(String[] args) {
        String sourceDirectoryPath = "D:/itheima-file";
        String destinationDirectoryPath = "D:/itheima-img";
        
        copyImages(sourceDirectoryPath, destinationDirectoryPath);
    }
    
    private static void copyImages(String sourceDirectoryPath, String destinationDirectoryPath) {
        File sourceDirectory = new File(sourceDirectoryPath);
        File destinationDirectory = new File(destinationDirectoryPath);
        
        if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
            throw new IllegalArgumentException("源目录不存在或不是目录");
        }
        
        if (!destinationDirectory.exists() || !destinationDirectory.isDirectory()) {
            throw new IllegalArgumentException("目标目录不存在或不是目录");
        }
        
        File[] files = sourceDirectory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile() && isImageFile(file.getName())) {
                    try {
                        copyFile(file, new File(destinationDirectory, file.getName()));
                        System.out.println("已复制文件：" + file.getAbsolutePath());
                    } catch (IOException e) {
                        System.out.println("复制文件时出现异常：" + e.getMessage());
                    }
                }
            }
        }
    }
    
    private static boolean isImageFile(String fileName) {
        String[] imageExtensions = {".jpg", ".jpeg", ".png", ".gif"};
        for (String extension : imageExtensions) {
            if (fileName.toLowerCase().endsWith(extension)) {
                return true;
            }
        }
        return false;
    }
    
    private static void copyFile(File sourceFile, File destinationFile) throws IOException {
        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(destinationFile)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }
}